package com.fyy.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fyy.base.exception.XCException;
import com.fyy.base.model.PageParams;
import com.fyy.base.model.PageResult;
import com.fyy.media.mapper.MediaFilesMapper;
import com.fyy.media.model.dto.QueryMediaParamsDto;
import com.fyy.media.model.dto.UploadFileParamsDTO;
import com.fyy.media.model.dto.UploadFileResultDTO;
import com.fyy.media.model.po.MediaFiles;
import com.fyy.media.service.MediaFileService;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author fyy
 * @version 1.0
 * @description TODO
 * @date 2024/8/2 22:58
 */
@Service
public class MediaFileServiceImpl implements MediaFileService {

    private static final Logger log = LoggerFactory.getLogger(MediaFileServiceImpl.class);

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MediaFilesMapper mediaFilesMapper;

    @Autowired
    private MediaFileService currentProxy;

    @Value("${minio.bucket.files}")
    private String bucketFiles;

    @Override
    public PageResult<MediaFiles> queryMediaFiels(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();

        //分页对象
        Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<MediaFiles> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return mediaListResult;

    }

    @Override
    public UploadFileResultDTO uploadFile(Long companyId, UploadFileParamsDTO uploadFileParamsDTO, String localFilePath) {
        File file = new File(localFilePath);
        if (!file.exists()) {
            XCException.cast("文件不存在");
        }
        String fileName = uploadFileParamsDTO.getFilename();
        String extension = fileName.substring(fileName.lastIndexOf("."));
        String mimeType = getMimeType(extension);
        String fileMD5 = getFileMD5(file);
        String defaultFolderPath = getDefaultFolderPath();
        //
        String objectName = defaultFolderPath + fileMD5 + extension;
        boolean b = addMediaFilesToMinIO(localFilePath, mimeType, bucketFiles, objectName);
        uploadFileParamsDTO.setFileSize(file.length());
        // 事物需要代理对象调用
        MediaFiles mediaFiles = currentProxy.addMediaFilesToDB(companyId, fileMD5, uploadFileParamsDTO, bucketFiles, objectName);
        UploadFileResultDTO uploadFileResultDTO = new UploadFileResultDTO();
        BeanUtils.copyProperties(mediaFiles, uploadFileResultDTO);
        return uploadFileResultDTO;
    }

    /**
     * 获取默认路径
     * @return 默认路径
     */
    private String getDefaultFolderPath() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String folder = simpleDateFormat.format(new Date()).replace("-", "/") + "/";
        return folder;
    }

    /**
     * 获取文件MD5值
     * @param file 文件
     * @return MD5
     */
    private String getFileMD5(File file) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            String fileMD5 = DigestUtils.md5Hex(fileInputStream);
            return fileMD5;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据扩展名获取对应的类型
     * @param extension
     * @return
     */
    private String getMimeType(String extension) {
        if (extension == null) {
            extension = "";
        }
        // 根据扩展名取出mimeType
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        // 通用 mimeType，字节流
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        if (extensionMatch != null) {
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }

    /**
     * @description 将文件写入minio
     * @param localFilePath 文件地址
     * @param mimeType 对象名称
     * @param bucket 桶名
     * @param objectName 对象名称
     * @return result
     * @author fyycode
     * @date 2024/8/2
     */
    public boolean addMediaFilesToMinIO(String localFilePath, String mimeType, String bucket, String objectName) {
        try {
            UploadObjectArgs testBucket = UploadObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .filename(localFilePath)
                    .contentType(mimeType)
                    .build();

            minioClient.uploadObject(testBucket);
            log.debug("上传文件到minio成功,bucket：{},objectName:{}", bucket, objectName);
            return true;
        }  catch (Exception e) {
            e.printStackTrace();
            log.debug("上传文件到minio失败,bucket：{},objectName:{},错误信息：{}", bucket, objectName, e.getMessage());
            XCException.cast("上传文件到文件系统失败");
        }
        return false;
    }

    /**
     * @description 将文件信息添加到文件表
     * @param companyId 机构id
     * @param fileMD5 文件md5
     * @param uploadFileParamsDTO 上传文件的信息
     * @param bucket 桶名
     * @param objectName 对象名称
     * @return MediaFiles
     * @author fyycode
     * @date 2024/8/2
     */
    @Transactional
    public MediaFiles addMediaFilesToDB(Long companyId, String fileMD5, UploadFileParamsDTO uploadFileParamsDTO, String bucket, String objectName) {
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMD5);
        if (mediaFiles == null) {
            mediaFiles = new MediaFiles();
            BeanUtils.copyProperties(uploadFileParamsDTO, mediaFiles);
            mediaFiles.setId(fileMD5);
            mediaFiles.setFileId(fileMD5);
            mediaFiles.setCompanyId(companyId);
            mediaFiles.setUrl("/" + bucket + "/" + objectName);
            mediaFiles.setFilePath(objectName);
            mediaFiles.setCreateDate(LocalDateTime.now());
            mediaFiles.setAuditStatus("002003");
            mediaFiles.setStatus("1");
            int insert = mediaFilesMapper.insert(mediaFiles);
            int a = 1 / 0;
            if (insert <= 0) {
                log.error("保存文件信息到数据库失败：{}", mediaFiles.toString());
                XCException.cast("保存文件信息失败");
            }
            log.debug("保存文件信息到数据库成功：{}", mediaFiles.toString());
        }
        return mediaFiles;
    }

}
